<template>
  <div class="content">
    <!-- 顶部搜索栏 -->
    <div class="top">
      <a-card :bordered="false">
        <a-space :size="20">
          <a-input-search
            v-model:value="user.homeName"
            style="width: 250px"
            placeholder="请输入商户名"
            @search="onSearch"
            size="large"
          >
            <template #enterButton>
              <a-button style="background-color: #409eff; color: white"
                >查询</a-button
              >
            </template>
          </a-input-search>
          <a-input-search
            v-model:value="user.status"
            style="width: 250px"
            placeholder="请输入商户状态"
            @search="likeSearch"
            size="large"
          >
            <template #enterButton>
              <a-button style="background-color: #409eff; color: white"
                >查询</a-button
              >
            </template>
          </a-input-search>
          <a-button type="primary" @click="resetParamr" ghost
            ><ReloadOutlined />重置</a-button
          >
          <a-button type="primary" @click="showModal" ghost
            ><PlusCircleOutlined />新增</a-button
          >
          <a-popconfirm
            title="确认删除？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="removeBachById"
            @cancel="cancel"
          >
            <a-button :disabled="!hasSelected" type="primary" danger ghost
              ><DeleteOutlined />批量删除</a-button
            >
          </a-popconfirm>
        </a-space>
      </a-card>
    </div>

    <!-- 表格数据展示 -->
    <div class="table">
      <a-card :bordered="false">
        <div>
          <a-spin tip="加载中" :spinning="false">
            <a-table
              :row-selection="{
                selectedRowKeys: state.selectedRowKeys,
                onChange: onSelectChange,
              }"
              :data-source="data"
              :pagination="false"
              :scroll="{ x: 1200, y: 800 }"
              :loading="loading"
            >
              <a-table-column
                fixed="left"
                key="name"
                title="持有人"
                data-index="name"
              />
              <a-table-column
                fixed="left"
                key="idCard"
                :ellipsis="true"
                title="身份证"
                data-index="idCard"
              />
              <a-table-column key="image" title="店铺主图" data-index="image">
                <template #default="{ record }">
                  <a-image :preview="false" :width="100" :src="record.image" />
                </template>
              </a-table-column>
              <a-table-column
                fixed="left"
                key="homeName"
                title="店铺名"
                data-index="homeName"
                :ellipsis="true"
              />
              <a-table-column
                :ellipsis="true"
                key="remark"
                title="简介"
                data-index="remark"
              />
              <a-table-column
                :ellipsis="true"
                key="address"
                title="地址"
                data-index="address"
              />
              <a-table-column key="status" title="状态">
                <template #default="{ record }">
                  <span>
                    <a-tag v-if="record.status === '通过'" color="success">
                      {{ record.status }}</a-tag
                    >
                    <a-tag v-else-if="record.status === '未通过'" color="error">
                      {{ record.status }}</a-tag
                    >
                    <a-tag v-else color="processing">
                      {{ record.status }}</a-tag
                    >
                  </span>
                </template>
              </a-table-column>
              <a-table-column width="200px" fixed="right" key="id" title="操作">
                <template #default="{ record }">
                  <div style="display: flex">
                    <div>
                      <a-button @click="edit(record.key)" type="link" ghost
                        >修改</a-button
                      >
                    </div>
                    <div style="margin-left: 10px">
                      <a-popconfirm
                        title="确认删除？"
                        ok-text="确认"
                        cancel-text="取消"
                        @confirm="remove(record.key)"
                        @cancel="cancel"
                      >
                        <a-button type="link" ghost danger> 删除 </a-button>
                      </a-popconfirm>
                    </div>
                  </div>
                </template>
              </a-table-column>
            </a-table>
          </a-spin>
        </div>
        <div
          style="
            height: 40px;
            width: 100%;
            margin-top: 30px;
            display: flex;
            justify-content: center;
          "
        >
          <a-pagination
            v-model:current="pageNo"
            v-model:page-size="pageSize"
            :total="total"
            @change="handlePageChange"
            :show-total="(total) => `共 ${total} 条`"
          />
        </div>
      </a-card>
    </div>

    <!-- 新增弹出框 -->
    <div>
      <a-modal
        v-model:open="open"
        @cancel="handleCancel"
        title="新增商户"
        :footer="null"
      >
        <div style="padding: 30px 0 20px 50px">
          <a-form
            ref="formRef"
            :model="business"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item ref="idCard" label="身份证" name="idCard">
              <a-input
                maxlength="18"
                v-model:value="business.idCard"
                size="large"
              />
            </a-form-item>
            <a-form-item ref="homeName" label="商户名" name="homeName">
              <a-input
                maxlength="20"
                v-model:value="business.homeName"
                size="large"
              />
            </a-form-item>
            <a-form-item ref="address" label="地址" name="address">
              <a-textarea
                size="large"
                v-model:value="business.address"
                :rows="4"
              />
            </a-form-item>
            <a-form-item ref="status" label="状态" name="status">
              <a-select
                v-model:value="business.status"
                size="large"
                style="width: 230px"
                :options="options"
              ></a-select>
            </a-form-item>
            <a-form-item ref="remark" label="简介" name="remark">
              <a-textarea
                size="large"
                v-model:value="business.remark"
                :rows="4"
              />
            </a-form-item>
            <a-form-item ref="image" label="商户图" name="image">
              <a-upload
                v-model:file-list="fileList"
                name="image"
                list-type="picture-card"
                class="avatar-uploader"
                :show-upload-list="false"
                :customRequest="customRequest"
                :before-upload="beforeUpload"
                @change="handleChange"
              >
                <img
                  style="height: 100px; width: 100px; border-radius: 10%"
                  v-if="business.image"
                  :src="business.image"
                  alt="avatar"
                />
                <div v-else>
                  <loading-outlined v-if="loading"></loading-outlined>
                  <plus-outlined v-else></plus-outlined>
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="save">保存</a-button>
              <a-button style="margin-left: 10px" @click="handleCancel"
                >取消</a-button
              >
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import {
  ReloadOutlined,
  PlusCircleOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import { upload } from "@/api/upload";
import {
  saveBusiness,
  list,
  echo,
  update,
  removeBatchByKeys,
} from "@/api/business";

const total = ref(0);
const pageNo = ref(1);
const pageSize = ref(10);
const data = ref([{}]);
const business = ref({
  key: null,
  idCard: "",
  homeName: "",
  remark: "",
  status: "",
  image: "",
  address: "",
});

const loading = ref(true);
onMounted(() => {
  setInterval(() => {
    loading.value = false;
  }, 1000);
  getAdmins();
});

//根据用户名进行模糊查询,没办法参数必须是一个对象
const user = ref({
  homeName: "",
  status: "",
});
//异步请求管理员数据
function getAdmins() {
  list(pageNo.value, pageSize.value, user.value).then((res) => {
    if (res.code === 200 && res.data != null) {
      data.value = res.data.data;
      total.value = res.data.total;
    }
  });
}

//商家数据模糊查询
function onSearch(searchValue) {
  user.value.homeName = searchValue;
  getAdmins();
}
//商家数据模糊查询
function likeSearch(searchValue) {
  user.value.status = searchValue;
  getAdmins();
}

//重置模糊查询数据
function resetParamr() {
  user.value.homeName = "";
  user.value.status = "";
  getAdmins();
}

//监听分页变化
function handlePageChange(param1, param2) {
  pageNo.value = param1;
  pageSize.value = param2;
  loading.value = true;
  setInterval(() => {
    loading.value = false;
  }, 1000);
  getAdmins();
}

//新增管理员弹框
const open = ref(false);
const showModal = () => {
  open.value = true;
};

//新增管理员操作
function save() {
  formRef.value
    .validate()
    .then(() => {
      //新增管理员
      if (business.value.key === null) {
        saveBusiness(business.value).then((res) => {
          if (res.code === 200) {
            message.success("新增成功！");
            //重新加载管理员数据
            getAdmins();
            open.value = false;
            business.value = {};
            business.value.key = null;
          }
        });
      } else {
        //修改管理员
        update(business.value).then((res) => {
          if (res.code === 200) {
            message.success("修改成功！");
            //重新加载管理员数据
            getAdmins();
            open.value = false;
            business.value = {};
          }
        });
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消新增管理员操作
function handleCancel() {
  open.value = false;
  business.value = {};
}

//管理员修改操作
function edit(id) {
  echo(id).then((res) => {
    if (res.code === 200 && res.data != null) {
      business.value = res.data;
      open.value = true;
    }
  });
}

//管理员确认删除回调操作
function remove(id) {
  removeBatchByKeys(id).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getAdmins();
    }
  });
}

//管理员取消删除回调操作
function cancel() {
  message.warning("取消删除！");
}

//数据校验
const formRef = ref();
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const rules = {
  idCard: [
    {
      required: true,
      message: "请输入身份证号",
      trigger: "change",
    },
  ],
  address: [
    {
      required: true,
      message: "请输入店铺地址",
      trigger: "change",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change",
    },
    {
      min: 11,
      max: 11,
      message: "长度为11个字符",
      trigger: "blur",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择商户状态",
      trigger: "blur",
    },
  ],
  image: [
    {
      required: true,
      message: "请上传商户图",
      trigger: "blur",
    },
  ],
  role: [
    {
      required: true,
      message: "请输入角色",
      trigger: "blur",
    },
  ],
  homeName: [
    {
      required: true,
      message: "请输入商户名",
      trigger: "blur",
    },
  ],
  remark: [
    {
      required: true,
      message: "请输入商户简介",
      trigger: "blur",
    },
  ],
};

//存储批量管理员id
const state = reactive({
  selectedRowKeys: [],
});
//当有一个或多个管理员被选中时触发按钮
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
//批量删除管理员
const removeBachById = () => {
  setTimeout(() => {
    state.selectedRowKeys = [];
  }, 1000);
  //删除后做操作
  removeBatchByKeys(state.selectedRowKeys).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getAdmins();
    }
  });
};
//当选中行改变时触发
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};

//头像上传部分
const fileList = ref([]);
function customRequest(file) {
  upload(file).then((res) => {
    if (res.code === 200) {
      business.value.image = res.data;
    }
  });
}

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("限定上传jpg/png格式!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("文件大于2MB!");
  }
  return isJpgOrPng && isLt2M;
};

const options = ref([
  {
    value: "通过",
    label: "通过",
  },
  {
    value: "审核中",
    label: "审核中",
  },
  {
    value: "未通过",
    label: "未通过",
  },
]);
</script>

<style scoped>
.options {
  margin-top: 10px;
}

.table {
  margin-top: 10px;
}

.avatar-uploader > .ant-upload {
  width: 50px;
  height: 50px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

:deep(.ant-card-body) {
  padding: 10px;
}
</style>>